<template>
  <div v-for="(item, index) in list" :key="index" class="component-item" @click="onItemClick(item)">
    <ScText v-bind="item" />
  </div>
  <StyledUploader @success="onImageUploaded" />
</template>
<script setup lang="ts">
import { v4 as uuidv4 } from 'uuid'
import { message } from 'ant-design-vue'
import { type TextComponentProps, type AllComponentProps } from '@/types/defaultProps'
import { type ComponentData } from '@/stores/editor'
import StyledUploader from '@/components/StyledUploader.vue'
import { type RespUploadData } from '@/types/respTypes'
import { imageDefaultProps } from '@/constant'
import { getImageDimensions } from '@/util/utils'

const onImageUploaded = (data: { resp: RespUploadData; file: File }) => {
  const { resp, file } = data
  const componentData: ComponentData = {
    name: 'sc-image',
    id: uuidv4(),
    props: {
      ...imageDefaultProps
    }
  }
  message.success('上传成功')
  componentData.props.src = resp.data.urls[0]
  getImageDimensions(file).then(({ width }) => {
    const maxWidth = 373
    componentData.props.width = (width > maxWidth ? maxWidth : width) + 'px'
    emit('on-item-click', componentData)
  })
}
defineProps<{
  list: TextComponentProps[]
}>()
const emit = defineEmits<{
  // (e: 'on-item-click', componentData: ComponentData): void
  (e: 'on-item-click', componentData: any): void
  // (e: 'update', value: string): void
}>()
const onItemClick = (item: Partial<AllComponentProps>) => {
  const componentData = {
    name: 'sc-text' as 'sc-text',
    id: uuidv4(),
    props: item
  }
  console.log(componentData, 'componentData')
  emit('on-item-click', componentData)
}
</script>

<style lang="scss" scoped>
.component-item {
  width: 100px;
  margin: 0 auto;
  margin-bottom: 15px;
}
.component-item > * {
  position: static !important;
}
</style>
